import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import store from '@/store'
import { message } from 'ant-design-vue'

/**
 * 单点登录
 */
const init = (callback) => {

  console.log('-------单点登录开始-------')
  let token = Vue.ls.get(ACCESS_TOKEN)
  let st = getUrlParam('v5ticket')
  let sevice = window._CONFIG['baseURL'] + '/'
  console.log(st)
  // if (token) {
  //   loginSuccess(callback)
  // } else {
    if (st) {
      validateSt(st, sevice, callback)
    } else {
      // window.location.href = sevice
      loginSuccess(callback)
    }
  // }
  console.log('-------单点登录结束-------')
}
const SSO = {
  init: init
}

function getUrlParam (paraName) {
  let url = document.location.toString()
  let arrObj = url.split('?')

  if (arrObj.length > 1) {
    let arrPara = arrObj[1].split('&')
    let arr

    for (let i = 0; i < arrPara.length; i++) {
      arr = arrPara[i].split('=')

      if (arr != null && arr[0] == paraName) {
        return arr[1]
      }
    }
    return ''
  } else {
    return ''
  }
}

function validateSt (ticket, sevice, callback) {

  let params = {
    ticket: ticket
  }
  store.dispatch('ValidateLogin', params).then(res => {

    //this.departConfirm(res)
    if (res.success) {
      loginSuccess(callback)
    } else {
      if (res.message){
        this.$notification.warn({
          message: '提示',
          description: res.message,
          duration: 3
        })
      }
      window.location.href = sevice
    }
  }).catch((err) => {
    console.log(err)
    window.location.href = sevice
  })
}

function loginSuccess (callback) {

  callback()
}

export default SSO